/**
 * All rights Reserved, Designed By liuchao
 *
 * @Title: RuntimeUtils.java
 * @Package com.huaju.utils
 * @Description: 执行操作系统命令工具类，封装返回信息
 * @author: liuchao
 * @date: 2018年12月10日 下午5:34:53
 * @version V1.0
 */
package cn.mntool.backup.utils;


import org.apache.commons.lang3.SystemUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName: RuntimeUtils
 * @Description: 执行操作系统命令工具类，封装返回信息
 * @author: liuchao
 */
public class RuntimeUtils {
    private RuntimeUtils(){}
    /**
     * 在有指定环境和工作目录的独立进程中执行指定的字符串命令
     *
     * @param cmd     执行的命令
     * @param workDir 工作目录
     * @return
     */
    public static List<String> exec(String cmd, File workDir) {
        String[] cmdArr = null;
        if (SystemUtils.IS_OS_WINDOWS) {
            cmdArr = new String[]{"cmd.exe", "/c", cmd};
        } else {
            getPermission(workDir);
            cmdArr = new String[]{"sh", "-c", cmd};
        }
        return exec(cmdArr, null, workDir);
    }

    /**
     * 获取linux执行权限
     */

    public static void getPermission( File workDir)
    {
        String[] cmdArr = new String[]{"sh", "-c", "chmod +x *"};
        exec(cmdArr, null, workDir);
    }

    /**
     * 在有指定环境和工作目录的独立进程中执行指定的字符串命令
     *
     * @param cmdarray 包含所调用命令及其参数的数组
     * @param envp     字符串数组，其中每个元素的环境变量的设置格式为 name=value
     * @param workDir  工作目录
     * @return
     */
    public static List<String> exec(String[] cmdarray, String[] envp, File workDir) {
        if (cmdarray == null || cmdarray.length == 0) {
            throw new RuntimeException("执行失败:命令不能为空");
        }
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdarray, envp, workDir);
            return doProcess(process);
        } catch (IOException e) {
            throw new RuntimeException("执行失败:请查看命令是否正确，或者是否有权限执行。",e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    public static List<String> doProcess(Process process) {
        List<String> resultList = new ArrayList<>();
        String encode;
        if (SystemUtils.IS_OS_WINDOWS) {
            encode = "GBK";
        } else {
            encode = "UTF-8";
        }

        try (
                InputStream in = process.getInputStream();
                BufferedReader inBuff = new BufferedReader(new InputStreamReader(in, encode));
                InputStream err = process.getErrorStream();
                BufferedReader errBuff = new BufferedReader(new InputStreamReader(err, encode));
        ) {
            // 正常输出
            String line = null;
            while ((line = inBuff.readLine()) != null) {
                resultList.add(line);
            }

            // 错误输出
            StringBuffer buff = new StringBuffer();
            while ((line = errBuff.readLine()) != null) {
                buff.append(line).append(System.lineSeparator());
            }

            // 判断结果
            if (process.waitFor() != 0) {
                throw new RuntimeException("执行失败:执行结果错误");
            }
        } catch (Exception e) {
            throw new RuntimeException("执行失败:",e);
        }
        return resultList;
    }
}
